<template>
  <div class="execution-log-container">
    <!-- 搜索表单组件 -->
    <search-form 
      :initial-search-form="searchForm"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 日志列表组件 -->
    <log-table 
      :log-data="tableData"
      :loading="tableLoading"
      :pagination="pagination"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @view-detail="handleViewDetail"
      @export="handleExport"
    />
    
    <!-- 详情对话框组件 -->
    <detail-dialog 
      v-model="detailVisible"
      :log-id="currentLogId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getTaskLogs, exportContrastResult } from '@/api/data-sync';
import { useRoute } from 'vue-router';

// 导入组件
import SearchForm from './components/SearchForm.vue';
import LogTable from './components/LogTable.vue';
import DetailDialog from './components/DetailDialog.vue';

// 获取路由实例，用于读取URL中的查询参数
const route = useRoute();

// 表格数据和加载状态
const tableData = ref<any[]>([]);
const tableLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  taskId: '',
  batchNo: '',
  status: null as number | null
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 详情对话框控制
const detailVisible = ref(false);
const currentLogId = ref('');

// 处理搜索
const handleSearch = (formData: any) => {
  searchForm.taskId = formData.taskId;
  searchForm.batchNo = formData.batchNo;
  searchForm.status = formData.status;
  pagination.currentPage = 1; // 重置为第一页
  fetchTaskLogs();
};

// 重置搜索
const handleReset = () => {
  searchForm.taskId = '';
  searchForm.batchNo = '';
  searchForm.status = null;
  pagination.currentPage = 1;
  fetchTaskLogs();
};

// 处理刷新
const handleRefresh = () => {
  fetchTaskLogs();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTaskLogs();
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchTaskLogs();
};

// 查看详情
const handleViewDetail = (row: any) => {
  currentLogId.value = row._id;
  detailVisible.value = true;
};

// 导出日志
const handleExport = (row: any) => {
  if (!row || !row._id) {
    ElMessage.warning('未找到日志ID，无法导出');
    return;
  }
  
  tableLoading.value = true;
  ElMessage.info('正在准备下载文件，请稍候...');
  
  exportContrastResult(row._id)
    .then(() => {
      ElMessage.success('导出成功');
    })
    .catch((error) => {
      console.error('导出失败:', error);
      ElMessage.error('导出失败：' + (error.message || '未知错误'));
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

// 获取执行日志列表
const fetchTaskLogs = async () => {
  try {
    tableLoading.value = true;
    
    const params = {
      taskId: searchForm.taskId || undefined,
      batchNo: searchForm.batchNo || undefined,
      status: searchForm.status !== null ? searchForm.status : undefined,
      page: pagination.currentPage,
      size: pagination.pageSize
    };
    
    const response: any = await getTaskLogs(params);
    
    if (response.code === 200) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || tableData.value.length;
    } else {
      ElMessage.error(response.message || '获取执行日志列表失败');
    }
  } catch (error) {
    console.error('获取执行日志列表出错:', error);
    ElMessage.error('获取执行日志列表出错');
  } finally {
    tableLoading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  // 从URL查询参数中获取taskId并设置到搜索表单
  const taskIdFromQuery = route.query.taskId as string;
  if (taskIdFromQuery) {
    searchForm.taskId = taskIdFromQuery;
  }
  fetchTaskLogs();
});
</script>

<style lang="scss" scoped>
.execution-log-container {
  // 主容器样式可以保留在这里
}
</style>